<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Modal, message } from 'ant-design-vue'
import dayjs from 'dayjs'

const router = useRouter()
const loading = ref(false)
const searchKeyword = ref('')
const formRef = ref()
const visible = ref(false)
const editingRecord = ref(null)
const confirmLoading = ref(false)
const formData = ref({
  name: '',
  description: '',
  status: '启用',
})

// Mock 数据（使用 ref 使其响应式）
const mockRoleList = ref([
  {
    id: 1,
    code: 'ROLE001',
    name: '人事专员',
    description: '负责员工档案管理、登记、查询和删除',
    status: '启用',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-20 14:20:00',
  },
  {
    id: 2,
    code: 'ROLE002',
    name: '复核专员',
    description: '负责档案和薪酬的复核工作',
    status: '启用',
    createTime: '2024-01-15 10:35:00',
    updateTime: '2024-01-18 09:15:00',
  },
  {
    id: 3,
    code: 'ROLE003',
    name: '部门经理',
    description: '可以查询本部门员工档案和薪酬信息',
    status: '启用',
    createTime: '2024-01-15 10:40:00',
    updateTime: '2024-01-15 10:40:00',
  },
  {
    id: 4,
    code: 'ROLE004',
    name: '普通员工',
    description: '可以查询自己的档案和薪酬信息',
    status: '启用',
    createTime: '2024-01-15 10:45:00',
    updateTime: '2024-01-15 10:45:00',
  },
  {
    id: 5,
    code: 'ROLE005',
    name: '系统专员',
    description: '负责系统设置，包括机构关系和职位设置',
    status: '启用',
    createTime: '2024-01-16 11:00:00',
    updateTime: '2024-01-16 11:00:00',
  },
  {
    id: 6,
    code: 'ROLE006',
    name: '薪酬专员',
    description: '负责薪酬标准登记、变更和发放登记',
    status: '启用',
    createTime: '2024-01-16 11:05:00',
    updateTime: '2024-01-16 11:05:00',
  },
  {
    id: 7,
    code: 'ROLE007',
    name: '权限管理员',
    description: '负责角色权限分配和管理',
    status: '启用',
    createTime: '2024-01-17 09:00:00',
    updateTime: '2024-01-17 09:00:00',
  },
])

const dataSource = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
})

const columns = [
  { title: '角色编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '角色名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '角色描述', dataIndex: 'description', key: 'description', width: 300 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', width: 180 },
  { title: '操作', key: 'action', width: 200 },
]

// 获取角色列表（使用 mock 数据）
const fetchRoleList = async () => {
  loading.value = true
  try {
    // 模拟 API 延迟
    await new Promise((resolve) => setTimeout(resolve, 300))

    let filteredList = [...mockRoleList.value]

    // 搜索过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filteredList = filteredList.filter(
        (item) =>
          item.code.toLowerCase().includes(keyword) ||
          item.name.toLowerCase().includes(keyword) ||
          item.description.toLowerCase().includes(keyword),
      )
    }

    // 分页处理
    const start = (pagination.value.current - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    const paginatedList = filteredList.slice(start, end)

    dataSource.value = paginatedList.map((item) => ({
      ...item,
      key: item.id,
    }))
    pagination.value.total = filteredList.length
  } catch (error) {
    console.error('获取角色列表失败:', error)
    dataSource.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchRoleList()
}

const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchRoleList()
}

const handleViewDetail = (record) => {
  router.push(`/role/${record.id}`)
}

const handleEdit = (record) => {
  editingRecord.value = record
  formData.value = {
    name: record.name || '',
    description: record.description || '',
    status: record.status || '启用',
  }
  visible.value = true
}

const handleDelete = async (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除角色"${record.name}"吗？删除后该角色将无法使用。`,
    async onOk() {
      try {
        // 模拟 API 延迟
        await new Promise((resolve) => setTimeout(resolve, 300))
        
        // 从 mockRoleList 中删除（逻辑删除，实际应该调用 API）
        const index = mockRoleList.value.findIndex((item) => item.id === record.id)
        if (index !== -1) {
          // 逻辑删除：将状态改为停用或从列表中移除
          // 这里我们选择从列表中移除（实际应该是逻辑删除，状态改为停用）
          mockRoleList.value.splice(index, 1)
        }
        
        message.success('删除成功')
        fetchRoleList() // 重新获取列表数据
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败，请稍后重试')
      }
    },
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch (error) {
    // 验证失败，不继续执行
    if (error?.errorFields) {
      return
    }
  }

  try {
    confirmLoading.value = true

    // 模拟 API 延迟
    await new Promise((resolve) => setTimeout(resolve, 300))

    if (editingRecord.value) {
      // 编辑角色
      const updateData = {
        name: formData.value.name,
        description: formData.value.description || '',
        status: formData.value.status || '启用',
      }

      // 更新 mockRoleList 中的数据
      const index = mockRoleList.value.findIndex((item) => item.id === editingRecord.value.id)
      if (index !== -1) {
        mockRoleList.value[index] = {
          ...mockRoleList.value[index],
          ...updateData,
          updateTime: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false,
          }).replace(/\//g, '-'),
        }
      }

      message.success('修改成功')
    }

    visible.value = false

    // 重新获取列表数据
    fetchRoleList()
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败，请稍后重试')
  } finally {
    confirmLoading.value = false
  }
}

onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">角色管理</h1>
      <p class="page-desc">查看和管理系统中的所有角色及其权限配置</p>
    </div>

    <div class="page-content">
      <div class="toolbar">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索角色编码、名称或描述"
          style="width: 300px"
          allow-clear
          @search="handleSearch"
          @clear="handleSearch"
        />
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="record.status === '启用' ? 'green' : 'red'">
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleViewDetail(record)">查看详情</a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)">删除</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      v-model:open="visible"
      title="编辑角色"
      width="600px"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="
        () => {
          visible = false
        }
      "
    >
      <a-form ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item
          v-if="editingRecord"
          label="角色编码"
          name="code"
        >
          <a-input
            :value="editingRecord?.code"
            placeholder="角色编码"
            disabled
            readonly
            style="background-color: #f5f5f5; cursor: not-allowed"
          />
        </a-form-item>
        <a-form-item
          label="角色名称"
          name="name"
          :rules="[{ required: true, message: '请输入角色名称' }]"
        >
          <a-input v-model:value="formData.name" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入角色描述"
            :rows="4"
          />
        </a-form-item>
        <a-form-item
          label="状态"
          name="status"
          :rules="[{ required: true, message: '请选择状态' }]"
        >
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="启用">启用</a-select-option>
            <a-select-option value="停用">停用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}
</style>

